using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Agreements;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.FormsManagement;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.ScriptEngine;
using PHSRAG.Utility;
using ScriptReference = PHSRAG.Insight21.ScriptEngine.ScriptReference;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
    /// Allows to specify sponsors for a protocol, set them as primary or secondary as required.
    /// Allows to request addition of a new sponsor to the database via an e-mail
    /// </summary>
    public partial class SponsorSelectionPage : BasePage
    {
        #region Constants

        private const string AnnunciatorTitle = "The following error(s) occurred...";
        private const string EnableNextKey = "enableNextKey_09C1E677-22AA-4bbf-824A-C6A525DAF55C";
        private const string PageCacheKey = "SponsorSelectionPage_2AE5B8E4-3D14-4427-B57E-637361715365";
        private const string ProtocolAccessLevelKey = "protocolAccessLevel_09C1E677-22AA-4bbf-824A-C6A525DAF55C";
        private const string ProtocolIdKey = "ProtocolId_B9FBD36B-FE85-40eb-AA19-3999BA542212";
        private const string ProtocolProcessIdKey = "PPId_5D4F2CB5-FFBD-4f84-AACE-F0365DD40561";
        private const string ProtocolVersionIdKey = "PVId_{E440E759-9400-4c49-987F-EBE02EA3D0B8}";
        private const string QuestionnaireAnswerIdKey = "QAId_68205A04-1794-4575-BAA3-90E305A66D5D";

        #endregion

        #region instance fields

        private ICachePolicy cachePolicy;
        private Hashtable pageCache;
        private ICachePolicy pageCachePolicy;
        private int pProcessId;
        private Protocol protocol;
        private int protocolId;
        private ProtocolProcess protocolProcess;
        private int pVersionId;
        private int qAnswerId;
        private QuestionnaireAnswer questionnaireAnswer;
        private bool removeQAOnCancel;
		
		//This flag is used to decide whether or not the headers should be displayed
		//If the page is to be displayed as a popup, then the header section is made invisible
        private bool showAsPopUp;
        private int userAccessLevel;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the protocol for which staffing is being reviewed or modified.  If it's not already
        /// in the cache, it loads it up based on the protocolId passed to the page, and caches the object
        /// </summary>
        private Protocol Protocol
        {
            get
            {
                string cacheKey = Protocol.ProtocolKey;
                protocol = cachePolicy.GetCachedObject(cacheKey) as Protocol;

                if ((protocol == null) || (protocolId != protocol.Id))
                {
                    protocol = new Protocol(cachePolicy);
                    protocol.Load(DataAccess.GetConnectionString(), protocolId);
                    cachePolicy.Cache(cacheKey, protocol);
                }
                return protocol;
            }
        }

        /// <summary>
        /// Gets the protocol process for which staffing is being reviewed or modified.  If it's not already
        /// in the cache, it loads it up based on the protocolProcessId passed to the page, and caches the 
        /// object
        /// </summary>
        private ProtocolProcess ProtocolProcess
        {
            get
            {
                protocolProcess = cachePolicy.GetCachedObject(ProtocolProcess.ProtocolProcessKey)
                    as ProtocolProcess;

                if ((protocolProcess == null) || (pProcessId != protocolProcess.Id))
                {
                    if (pProcessId > 0)
                    {
                        protocolProcess = ProtocolProcess.GetProtocolProcess(
                            DataAccess.GetConnectionString(), pProcessId, cachePolicy, null);
                        cachePolicy.Cache(ProtocolProcess.ProtocolProcessKey, protocolProcess);
                    }
                    else
                    {
                        protocolProcess = null;
                    }
                }
                return protocolProcess;
            }
        }

        /// <summary>
        /// Indicates whether or not the Next button should be enabled
        /// </summary>
        private bool EnableNext
        {
            get
            {
                object enable = pageCachePolicy.GetCachedObject(EnableNextKey);
                return (enable != null) ? (bool) enable : false;
            }
            set { pageCachePolicy.Cache(EnableNextKey, value); }
        }

        #endregion

        #region Page Events

        /// <summary>
        /// Loads the page. Initializes the breadcrumb. Pulls the data from incoming cache and stores them in the page cache.
        /// Loads the sponsor types from the database into a dropdownlist
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                breadCrumb.Add(
                    "Sponsor / Funding",
                    Settings.GetKeyValue("SubModuleNavigation.Humans.SponsorSelectionPageURL", ""),
                    Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));


                pageCache = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();

                if (!IsPostBack)
                {
                    Hashtable incomingPageHash = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                    if (incomingPageHash != null)
                    {
                        userAccessLevel = Convert.ToInt32(incomingPageHash[Keys.ProtocolAccessKey]);

                        protocolId = Convert.ToInt32(incomingPageHash[Keys.ProtocolIdKey]);
                        pageCache[ProtocolIdKey] = protocolId;
                        pVersionId = Convert.ToInt32(incomingPageHash[Keys.ProtocolVersionIdKey]);
                        pageCache[ProtocolVersionIdKey] = pVersionId;

                        qAnswerId = Convert.ToInt32(incomingPageHash[Keys.QuesionnaireAnswerIdKey]);
                        pageCache[QuestionnaireAnswerIdKey] = qAnswerId;
                        questionnaireAnswer = new QuestionnaireAnswer(cachePolicy);
                        questionnaireAnswer.Load(DataAccess.ConnectionString, qAnswerId);
                        UserContext loggedInUserContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
                        questionnaireAnswer.LastModifiedByAdmPersonId = loggedInUserContext.PersonId;
                        questionnaireAnswer.Cache();

                        pProcessId = Convert.ToInt32(incomingPageHash[Keys.ProtocolProcessIdKey]);
                        pageCache[ProtocolProcessIdKey] = pProcessId;

                        protocol = new Protocol(cachePolicy);
                        protocol.Load(DataAccess.ConnectionString, protocolId);
                        protocol.Cache();

                        protocolProcess = ProtocolProcess.GetProtocolProcess(DataAccess.ConnectionString,
                            pProcessId, cachePolicy, null);

                        protocolProcess.Cache();

                        if (incomingPageHash.ContainsKey(Keys.ShowAsPopUp))
                        {
                            showAsPopUp = Convert.ToBoolean(incomingPageHash[Keys.ShowAsPopUp]);
                        }
                        pageCache[Keys.ShowAsPopUp] = showAsPopUp;

                        if (incomingPageHash.ContainsKey(Keys.RemoveQAOnCancel))
                        {
                            removeQAOnCancel = Convert.ToBoolean(incomingPageHash[Keys.RemoveQAOnCancel]);
                            pageCache[Keys.RemoveQAOnCancel] = removeQAOnCancel;
                        }

                        pageCache[ProtocolAccessLevelKey] = userAccessLevel;
                        pageCachePolicy.Cache(PageCacheKey, pageCache);
                        pageCachePolicy.UnCache(Keys.IncomingDataKey);
                    }
                    else
                    {
                        userAccessLevel = (int) pageCache[ProtocolAccessLevelKey];
                        protocolId = (int) pageCache[ProtocolIdKey];
                        pVersionId = (int) pageCache[ProtocolVersionIdKey];
                        qAnswerId = (int) pageCache[QuestionnaireAnswerIdKey];
                        pProcessId = (int) pageCache[ProtocolProcessIdKey];
                        showAsPopUp = (bool) pageCache[Keys.ShowAsPopUp];
                        removeQAOnCancel = (bool) pageCache[Keys.RemoveQAOnCancel];
                        questionnaireAnswer = new QuestionnaireAnswer(cachePolicy);
                        questionnaireAnswer = (QuestionnaireAnswer) cachePolicy.GetCachedObject(questionnaireAnswer.CacheKey());
                        protocol = new Protocol(cachePolicy);
                        protocol = (Protocol) cachePolicy.GetCachedObject(protocol.CacheKey());
                        protocolProcess = new ProtocolProcess(cachePolicy);
                        protocolProcess = (ProtocolProcess) cachePolicy.GetCachedObject(ProtocolProcess.ProtocolProcessKey);
                    }

                    if (questionnaireAnswer == null)
                    {
                        annunciator.Message = "Failed to load Sponsor Selection Page: Invalid context";
                        sponsorDetailsPanel.Enabled = false;
                        return;
                    }
                }
                else
                {
                    userAccessLevel = (int) pageCache[ProtocolAccessLevelKey];
                    protocolId = (int) pageCache[ProtocolIdKey];
                    pVersionId = (int) pageCache[ProtocolVersionIdKey];
                    qAnswerId = (int) pageCache[QuestionnaireAnswerIdKey];
                    pProcessId = (int) pageCache[ProtocolProcessIdKey];
                    showAsPopUp = (bool) pageCache[Keys.ShowAsPopUp];
                    removeQAOnCancel = (bool) pageCache[Keys.RemoveQAOnCancel];
                    questionnaireAnswer = new QuestionnaireAnswer(cachePolicy);
                    questionnaireAnswer = (QuestionnaireAnswer) cachePolicy.GetCachedObject(questionnaireAnswer.CacheKey());
                    protocol = new Protocol(cachePolicy);
                    protocol = (Protocol) cachePolicy.GetCachedObject(protocol.CacheKey());

                    protocolProcess = (ProtocolProcess) cachePolicy.GetCachedObject(ProtocolProcess.ProtocolProcessKey);
                }

                //if page is being shown as popup, then hide the header section
                headerSection.Visible = !showAsPopUp;
                next.Visible = EnableNext;
            }
            catch (Exception ex)
            {
                ExceptionReport.WriteToEventLog("SponsorSelectionPage.Load(): Failed to load the page", ex, true, ExceptionReport.ReportType.Error);
                annunciator.Message = "Failed to load the page";
            }
            finally
            {
                protocolDetailHeader.ProtocolID = protocolId;
                //Set the humansubmodule Navigation links
                humansSubModNavigation.ProtocolProcess = ProtocolProcess;
                humansSubModNavigation.Protocol = Protocol;
            }
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.header.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.humansSubModNavigation.Navigate += new PHSRAG.Insight21.InsightWebControls.HumansSubModuleNavigation.NavigateEventHandler(this.OnHumansSubModNavigate);
            this.breadCrumb.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnBreadCrumbNavigate);
            this.searchSponsor.Click += new ImageClickEventHandler(OnSearchSponsorClick);
            this.cancel.Click += new ImageClickEventHandler(OnCancel);
            this.next.Click += new ImageClickEventHandler(OnNextClick);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion

        #region Control Events

        /// <summary>
        /// Resets the subnavigation selected link before the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnBreadCrumbNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                humansSubModNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link before the header or the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                humansSubModNavigation.Reset();
                humansSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Constructs and caches a hashtable of data for use by the page to which nagivation leads
        /// </summary>
        private void OnHumansSubModNavigate()
        {
            try
            {
                Hashtable outgoingData = new Hashtable();
                outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
                outgoingData.Add(Keys.ProtocolIdKey, protocolId);
                outgoingData.Add(Keys.ProtocolProcessIdKey, pProcessId);
                outgoingData.Add(Keys.ProtocolVersionIdKey, pVersionId);
                outgoingData.Add(Keys.QuesionnaireAnswerIdKey, qAnswerId);
                pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Search for sponsor(s) based on the selected nameType and the sponsor name entered.
        /// The list of sponsors found are populated into a dropdownlist with their selected name types as display and id's as the values
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnSearchSponsorClick(object sender, ImageClickEventArgs e)
        {
            sponsorList.Items.Clear();
            EnableNext = next.Visible = true;
            addSponsorLink.Enabled = true;
            Sponsors sponsorCollection = new Sponsors(cachePolicy);
            string name = string.Empty;
            string shortName = string.Empty;
            switch (nameType.SelectedIndex)
            {
                case 0:
                    name = sponsorName.Text.Trim();
                    break;
                case 1:
                    shortName = sponsorName.Text.Trim();
                    break;
            }
            sponsorCollection.Load(DataAccess.ConnectionString, name, shortName);
            if (sponsorCollection.SponsorList.Count > 0)
            {
                pickOne.Visible = true;
                sponsorList.Visible = true;

                switch (nameType.SelectedIndex)
                {
                    case 0:
                        sponsorList.DataSource = sponsorCollection.SponsorList;
                        sponsorList.DataTextField = "NameAndType";
                        sponsorList.DataValueField = "Id";
                        sponsorList.DataBind();
                        break;
                    case 1:
                        sponsorList.DataSource = sponsorCollection.SponsorList;
                        sponsorList.DataTextField = "ShortNameAndType";
                        sponsorList.DataValueField = "Id";
                        sponsorList.DataBind();
                        break;
                }
            }
            else
            {
                annunciator.Message = "No results are found.  Please search again or click the \"Add a Sponsor\" link.";
                pickOne.Visible = false;
                sponsorList.Visible = false;
            }
        }

        /// <summary>
        /// Sets the questionnaire answer's name to the name of the sponsor selected.
        /// Adds a mapping between the protocol and and sponsor and finally
        /// the sponsors questionnaire is shown to the user.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnNextClick(object sender, ImageClickEventArgs e)
        {
            try
            {
                if (sponsorType.SelectedIndex == -1)
                {
                    annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                    annunciator.Message = "Please select the type of the sponsor.";
                    return;
                }

                Constants.SponsorTypes selectedSponsorType = (Constants.SponsorTypes) Enum.Parse(typeof (Constants.SponsorTypes), sponsorType.SelectedIndex.ToString(), true);

                switch (selectedSponsorType)
                {
                    case Constants.SponsorTypes.GovernmentFoundation:
                        if (sponsorList.Items.Count == 0)
                        {
                            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                            annunciator.Message = "No results are found.  Please search again or click the \"Add a Sponsor\" link.";
                            return;
                        }
                        if (sponsorList.SelectedIndex == -1)
                        {
                            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                            annunciator.Message = "No sponsor is selected.";
                            next.Visible = true;
                            return;
                        }
                        //questionnaire answer
                        questionnaireAnswer.ExternalId = int.Parse(sponsorList.SelectedValue);
                        questionnaireAnswer.Name = sponsorList.SelectedItem.Text;
                        break;

                    case Constants.SponsorTypes.CorporateSponsor:
                        if (sponsorList.Items.Count == 0)
                        {
                            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                            annunciator.Message = "No results are found.  Please search again or click the \"Add a Sponsor\" link.";
                            return;
                        }
                        if (sponsorList.SelectedIndex == -1)
                        {
                            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                            annunciator.Message = "No sponsor is selected.";
                            return;
                        }
                        //questionnaire answer
                        questionnaireAnswer.ExternalId = int.Parse(sponsorList.SelectedValue);
                        questionnaireAnswer.Name = sponsorList.SelectedItem.Text;
                        break;

                    case Constants.SponsorTypes.InstitutionalAward:
                        if (sponsorList.Items.Count == 0)
                        {
                            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                            annunciator.Message = "No results are found.  Please search again or click the \"Add a Sponsor\" link.";
                            return;
                        }
                        if (sponsorList.SelectedIndex == -1)
                        {
                            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                            annunciator.Message = "No sponsor is selected.";
                            return;
                        }
                        //questionnaire answer
                        questionnaireAnswer.ExternalId = int.Parse(sponsorList.SelectedValue);
                        questionnaireAnswer.Name = sponsorList.SelectedItem.Text;

                        //Add the admPersonId of the user last modified or added the sponsor
                        UserContext loggedInUserContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
                        questionnaireAnswer.LastModifiedByAdmPersonId = loggedInUserContext.PersonId;
                        break;
                }


                Script sponsorScript =
                    (Script) questionnaireAnswer.QuestionnaireVersion.Scripts[FormsManagement.Constants.ScriptType.AnswerFiller];

                if (sponsorScript != null)
                {
                    using (ScriptEngineHost scriptHost =
                        new ScriptEngineHost(
                            string.Format("{0}{1}", questionnaireAnswer.QuestionnaireVersion.Id,
                                ScriptEngine.Constants.RootMoniker.AnswerFillerScriptMoniker),
                            ScriptEngine.Constants.RootNamespaces.AnswerFillerScript,
                            true))
                    {
                        ArrayList refs = ScriptReference.GetAllScriptReferences(
                            DataAccess.GetConnectionString());

                        for (int i = 0; i < refs.Count; ++i)
                        {
                            ScriptReference reference = (ScriptReference) refs[i];
                            scriptHost.AddDLLReference(reference.Path);
                        }


                        // add the type of the sponsor as an intrinsic
                        scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.SponsorType, selectedSponsorType);

                        Protocol theProtocol = new Protocol(cachePolicy);
                        theProtocol.Load(DataAccess.GetConnectionString(), protocolId);
                        // add this protocol as an intrinsic.
                        scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.Protocol, theProtocol);

                        // add the connection string
                        scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.ConnectionString,
                            DataAccess.GetConnectionString());

                        // add the QuestionnaireAnswer
                        scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.QuestionnaireAnswer,
                            questionnaireAnswer);

                        // add the versionhttp://localhost/Insight/Humans/ActiveProtocols.aspx
                        scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.ProtocolVersion, questionnaireAnswer.QuestionnaireVersion);

                        // add the caching policy
                        scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.CachePolicy, cachePolicy);

                        // compile and run the script.
                        if (scriptHost.Compile(sponsorScript))
                        {
                            scriptHost.RunScript(sponsorScript,
                                ScriptEngine.Constants.AssemblyType.AnswerFillerScript,
                                ScriptEngine.Constants.MethodsToRun.Main);
                        }
                    }
                }

                if (selectedSponsorType == Constants.SponsorTypes.None)
                {
                    // cache required data and redirect back to overview page
                    Hashtable dataOutgoing = new Hashtable();
                    dataOutgoing.Add(Keys.ProtocolIdKey, protocolId);
                    dataOutgoing.Add(Keys.ProtocolProcessIdKey, protocolProcess.Id);
                    dataOutgoing.Add(Keys.ProtocolAccessKey, userAccessLevel);
                    dataOutgoing.Add(Keys.ShowAsPopUp, showAsPopUp);
                    pageCachePolicy.Cache(Keys.IncomingDataKey, dataOutgoing);
                    pageCachePolicy.UnCache(EnableNextKey);

                    // now that it's saved, redirect the user to the ProtocolProcessOverview page.
                    Page.Response.Redirect(
                        Settings.GetKeyValue("SubModuleNavigation.Humans.ProtocolProcessOverviewURL", ""), true);
                }
                else
                {
                    Hashtable outgoingData = new Hashtable();
                    outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
                    outgoingData.Add(Keys.ProtocolIdKey, protocolId);
                    outgoingData.Add(Keys.ProtocolProcessIdKey, pProcessId);
                    outgoingData.Add(Keys.ProtocolVersionIdKey, pVersionId);
                    outgoingData.Add(Keys.QuestionnaireVersionIdKey, questionnaireAnswer.QuestionnaireVersionId);
                    outgoingData.Add(Keys.QuesionnaireAnswerIdKey, questionnaireAnswer.Id);
                    outgoingData.Add(Keys.ShowAsPopUp, showAsPopUp);
                    outgoingData.Add(Keys.RemoveQAOnCancel, removeQAOnCancel);
                    pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
                    pageCachePolicy.UnCache(EnableNextKey);
                    Page.Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.AnswerQuestionnairePageURL", ""), false);
                }
            }
            catch
            {
                annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                annunciator.Message = "Failed to add the sponsor.";
                next.Visible = EnableNext;
            }
        }

        /// <summary>
        /// The nameType radiobuttonlist posts back only the first time the user selects an option.
        /// This eventhandler enables the search button and sets the autopostback property on the radiobuttonlist to false.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnNameTypeSelectedIndexChanged(object sender, EventArgs e)
        {
            searchSponsor.Visible = true;
            nameType.AutoPostBack = false;
        }

        /// <summary>
        /// Navigates to the ProtocolProcessOverview page
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnCancel(object sender, ImageClickEventArgs e)
        {
            if (removeQAOnCancel)
            {
                ProtocolVersion pV = new ProtocolVersion(cachePolicy);
                pV.Load(DataAccess.ConnectionString, pVersionId);
                pV.DeleteQuestionnaireAnswer(questionnaireAnswer.Id);
            }

            pageCachePolicy.UnCache(EnableNextKey);

            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ProtocolIdKey, protocolId);
            outgoingData.Add(Keys.ProtocolProcessIdKey, pProcessId);
            outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
            outgoingData.Add(Keys.ShowAsPopUp, showAsPopUp);
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

            if (!showAsPopUp)
            {
                Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.ProtocolProcessOverviewURL", ""));
            }
            else
            {
                ClientScript.RegisterStartupScript(GetType(), "CloseWindow", "<script>javascript:window.close();</script>");
            }
        }

        /// <summary>
        /// Shows either the search panel to search existing sponsors matching the specified criteria or 
        /// the internal department panel to specity the department name and fund number based on the type of the sponsor selected.
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnSponsorTypeChanged(object sender, EventArgs e)
        {
            Constants.SponsorTypes selectedSponsorType = (Constants.SponsorTypes) Enum.Parse(typeof (Constants.SponsorTypes), sponsorType.SelectedIndex.ToString(), true);
            switch (selectedSponsorType)
            {
                case Constants.SponsorTypes.GovernmentFoundation:
                case Constants.SponsorTypes.CorporateSponsor:
                case Constants.SponsorTypes.InstitutionalAward:
                    searchPanel.Visible = true;
                    next.Visible = false;
                    break;
                case Constants.SponsorTypes.DepartmentFunds:
                    searchPanel.Visible = false;
                    next.Visible = true;
                    break;
                case Constants.SponsorTypes.None:
                    searchPanel.Visible = false;
                    next.Visible = true;
                    break;
            }
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = AnnunciatorTitle;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        #endregion
    }
}